package threadUtils.demo07;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 性能低下，不建议使用
 */
public class WriterReadLockExample01 {

    private static class LockExample {

        private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
        private final Lock r = readWriteLock.readLock();
        private final Lock w = readWriteLock.writeLock();

        private final List<String> list = new ArrayList<>();

        public String getByIndex(int index) {
            r.lock();
            try {
                return list.get(index);
            } finally {
                r.unlock();
            }
        }

        public void add(String str) {
            w.lock();
            try {
                list.add(str);
            } finally {
                w.unlock();
            }
        }

        public String pop() {
            r.lock();
            try {
                return list.stream().findFirst().orElse("first");
            } finally {
                r.unlock();
            }
        }
    }

    public static void main(String[] args) {

        LockExample lockExample = new LockExample();

        new Thread(() -> {
            lockExample.add("xxx");
            String pop = lockExample.pop();

            System.out.println(Thread.currentThread().getName() + "获取：" + pop);
        }, "T-1").start();

        new Thread(() -> {

            String byIndex = lockExample.getByIndex(0);
            System.out.println(Thread.currentThread().getName() + "获取：" + byIndex);

            lockExample.add("cc");
        }, "T-2").start();

        new Thread(() -> {

            String byIndex = lockExample.getByIndex(0);
            System.out.println(Thread.currentThread().getName() + "获取：" + byIndex);

            String pop = lockExample.pop();
            System.out.println(Thread.currentThread().getName() + "获取：" + pop);

        }, "T-3").start();

    }
}
